package com.gopay.bis.cmb.ebank.operation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cmb.b2b.B2BResult;
import com.cmb.b2b.FirmbankCert;
import com.cmb.b2b.SelfIssuedCert;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2bMessage;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2bPayResult;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ICertHelper;

/** 
 * @ClassName: CmbB2bCerthelper 
 * @Description: 招行b2b 工具类
 * @author w_jiqing 
 * @date 2016年8月29日 下午2:27:36  
 */ 
public class CmbB2bCerthelper implements ICertHelper{
    private static Log logger = LogFactory.getLog(CmbB2bCerthelper.class);

    @Override
    public String sign(BaseMessage bsaeMessage) throws GopayException {
        String signStr = "";
        CmbB2bMessage message =(CmbB2bMessage) bsaeMessage;
        BankLogUtils.printB2BSignPlainLog(message);
        //读取证书
        byte[] bPfXFile =null;
        File fCert = new File(message.getPrivateKeyPath());
        if(fCert.exists()){
            int iFileLen = (int) fCert.length();
            if(iFileLen == 0){
                throw new GopayException("Cert file is empty.");
            }
            bPfXFile = new byte[iFileLen];
            FileInputStream fis = null;
            try{
                fis = new FileInputStream(message.getPrivateKeyPath());
                fis.read(bPfXFile,0,iFileLen);
                fis.close();
            } catch(IOException ex){
                throw new GopayException("Read cert file error.");
            }
        }else{
            throw new GopayException("Cert file is not exist.");
        }
        //证书初始化
        B2BResult bRet = SelfIssuedCert.initCert(bPfXFile,message.getPrivatePwd().toCharArray());
        if(bRet.isError()){
            throw  new GopayException("Signature Error."+bRet.getErrorMsg());
        }
        //签名
        bRet = SelfIssuedCert.signature(message.getPlainMessage().getBytes());
        if(bRet.isError()){
            throw new GopayException("Signature Error."+bRet.getErrorMsg());
        }else{
            logger.info("Signature  Success .");
            signStr = bRet.getResultBase64Str();
        } 
        BankLogUtils.printB2BSignSignatureLog(message, signStr);
        return signStr;
    }

    @Override
    public Object verify(BaseMessage bsaeMessage) throws GopayException {
        boolean result =false;        
        try {
            CmbB2bPayResult message =(CmbB2bPayResult) bsaeMessage;
            BankLogUtils.printB2BVerifyPlainLog(message);       
            String sBase64PubKey = message.getPublicKeyPath(); //银行公钥
            //初始化公钥，验证签名
            B2BResult bRet = FirmbankCert.initPublicKey(sBase64PubKey);
            if(bRet.isError()){
                throw new GopayException("Init public key error:"+bRet.getErrorMsg());
            }
            bRet =FirmbankCert.verifySignatureByPubKey(message.getPlainMessage().getBytes("GBK"), message.getSignMessage());
            if(bRet.isError()){
                throw new GopayException("Verify Signature Error:"+bRet.getErrorMsg());
            }else{
                result =true;           
            }
            BankLogUtils.printB2BVerifyResultLog(message, result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new GopayException(ProcCodeConstants.PROC_CODE_100E6030);
        }             
        return result;
    }
    

}
